package com.github.catvod.utils;

import android.util.Base64;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class CgImageUtil {
    private static final String IV = "97b60394abc2fbe1";
    private static final String KEY = "f5d965df75336270";

    public static String loadBackgroundImage(String bgUrl) {
        if (isCdnImg(bgUrl)) {
            try {
                Request request = new Request.Builder().url(bgUrl).build();
                Response response = new OkHttpClient().newCall(request).execute();
                ResponseBody body = response.body();
                if (body != null) {
                    byte[] imageBytes = body.bytes();
                    // 进行base64编码
                    String base64str = Util.base64EncodeDEFAULT(imageBytes);
                    byte[] decrypt = AESEncryption.cg51decrypt(base64str, KEY, IV, AESEncryption.CBC_PKCS_7_PADDING);
                    return Base64.encodeToString(decrypt, Base64.DEFAULT);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }else {
            return "url(\"" + bgUrl + "\")";
        }
        return null;
    }
    private static boolean isCdnImg(String path) {
        if (path == null || path.isEmpty()) {
            return false;
        }
        if (path.contains("/xiao/")) {
            return true;
        }
        return path.contains("/upload");
    }
}
